package com.group9.handinhand.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.DuplicateConnectionException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.group9.handinhand.dao.SocialUserDao;
import com.group9.handinhand.dao.model.SocialUser;

@Transactional
@Service("socialUserService")
public class SocialUserServiceImpl implements SocialUserService {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SocialUserDao socialUserDao;
	/**
	 * Loads the user's social details
	 * @param userId
	 * @throws UsernameNotFoundException
	 * @throws DataAccessException
	 * @return userDetails
	 */
	@Override
	public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
		UserDetails userDetails = userService.getUserByEmail(userId);
        return (SocialUserDetails) userDetails;
	}
	
	@Override
	public void addConnection(String userId, Connection<?> connection) {
		try {
			ConnectionData data = connection.createData();
			int rank = socialUserDao.selectMaxRankByUserIdAndProviderId(userId, data.getProviderId());
			SocialUser socialUser = new SocialUser();
			socialUser.buildFromConnectionData(data);
			socialUser.setRank(rank);
			socialUser.setUser(userService.getUserByEmail(userId).convertToModelObject());
			socialUserDao.saveSocialUser(socialUser);
		} catch (DuplicateKeyException e) {
			throw new DuplicateConnectionException(connection.getKey());
		}
	}

	@Override
	public void updateConnection(String userId, Connection<?> connection) {
		ConnectionData data = connection.createData();
		SocialUser socialUser = socialUserDao.get(userId, data.getProviderId(), data.getProviderUserId());
		socialUser.buildFromConnectionData(data);
		socialUserDao.updateSocialUser(socialUser);
	}

	@Override
	public List<String> findUserIdsByProviderIdAndProviderUserId(String providerId, String providerUserId) {
		return socialUserDao.findUserIdsByProviderIdAndProviderUserId(providerId, providerUserId);
	}

}
